package com.yonyou.gmmc.service.pointactivity.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yonyou.gmmc.service.pointactivity.model.TmDealer;
import com.yonyou.gmmc.service.pointactivity.model.TmRegion;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.gmmc.service.pointactivity.constant.PointActivityConstant;
import com.yonyou.gmmc.service.pointactivity.model.TmKeep;
import com.yonyou.gmmc.service.pointactivity.service.LinkAgeService;
import com.yonyou.gmmc.service.pointactivity.service.ReservationService;
import com.yonyou.gmmc.service.pointactivity.service.TtWinnerRecordService;

import io.swagger.annotations.Api;

/*
 * 
 * 五周年感恩回馈活动
 * */
@RestController
@RequestMapping(value = PointActivityConstant.BASE_PATH + "/" + PointActivityConstant.VERSION)
@Api("五周年感恩回馈活动")
public class LinkAgeController {
	private Logger logger = Logger.getLogger(LinkAgeController.class);

	@Autowired
	private LinkAgeService linkageService;
	
    // 活动类型
    private Integer ACTIVITY_TYPE = 3;
    // 操作人
    private Long OPERATION_BY = 111111111L;
    
    @Autowired
    private ReservationService reservationService;
    
    @Autowired
    private TtWinnerRecordService ttWinnerRecordService;
	
    /**
     * 这个方法会在当前这个类(Controller)任何一个方法调用之前调用一次
     *
     * @param req
     */
    @ModelAttribute
    public void recordVisit(HttpServletRequest req) {
        String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);
//        openId = null == openId ? "oXrcfuGUU-0hRB1GnYNtjl-PvcsM" : openId;
        try {

            if (com.yonyou.gmmc.service.pointactivity.util.StringUtils.isNull(openId))
                throw new Exception("openId为空.!");

            Map<String, Object> param = new HashMap<String, Object>();
            param.put("openId", openId);
            param.put("activityType", ACTIVITY_TYPE);
//            //判断是否获取到用户所在省份地址信息
            if(req.getParameter("province")==null || "".equals(req.getParameter("province"))){
                //当省份为空时，查询用户所购车辆所在地省份
                String province=reservationService.getCarAndProvince(openId);
                param.put("province", province);
            }else {
                param.put("province", req.getParameter("province"));
            }
            param.put("createBy", OPERATION_BY);
            param.put("updateBy", OPERATION_BY);

            ttWinnerRecordService.recordVisit(param);
        } catch (Exception e) {
            logger.info("五周年购车回赠活动-记录用户访问次数.获取到openId:" + openId + ",访问记录异常.");
        }
    }

	@RequestMapping("queryKeepProvince")
	public @ResponseBody Map<String, Object> queryMsgSencond(HttpServletRequest request, HttpServletResponse response, String provicecode, String citycode, String dealerCode) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {

			if (!StringUtils.isEmpty(provicecode)) {
				TmRegion provice = linkageService.checkOutProvince(provicecode);
				if (provice != null) {
					resultMap.put("provice", provice.getRegionName());
				}
			}
			if (!StringUtils.isEmpty(citycode)) {
				TmRegion city = linkageService.checkOutProvince(provicecode);
				if (city != null) {
					resultMap.put("city", city.getRegionName());
				}
			}
			if (!StringUtils.isEmpty(dealerCode)) {
				TmDealer dealer = linkageService.chenkOutDealer(dealerCode);
				if (dealer != null) {
					resultMap.put("dealer", dealer.getDealerName());
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());

		}
		return resultMap;

	}

	/**
	 * 查询省份
	 */
	@RequestMapping(value = "/getProvince", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody List<TmRegion> getProvince() {
		List<TmRegion> list = new ArrayList<TmRegion>();
		try {
			list = linkageService.getProvince();
		} catch (Exception e) {
			logger.error(new Exception(e));
		}
		return list;
	}

	/**
	 * 根据省份查询城市列表
	 */
	@RequestMapping(value = "/getCity", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody List<TmRegion> getCity(@RequestParam("regionCode") String regionCode) {
		List<TmRegion> list = new ArrayList<TmRegion>();
		try {
			list = linkageService.getCity(regionCode);
		} catch (Exception e) {
			logger.error(new Exception(e));
		}
		return list;
	}

	/**
	 * 根据城市名称查询当地经销商
	 */
	@RequestMapping(value = "/getDealer", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody List<TmDealer> getDealer(@RequestParam("regionCode") String regionCode) {
		List<TmDealer> list = new ArrayList<TmDealer>();
		try {
			list = linkageService.getDealer(regionCode);
		} catch (Exception e) {
			logger.error(new Exception(e));
		}
		return list;

	}

	/*
	 * 根据当地经销商查询意向车型
	 */
	@RequestMapping(value = "/getModel", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> findByModel(@RequestParam("dealerCode") String dealerCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = linkageService.getModel(dealerCode);
		} catch (Exception e) {
			logger.error(new Exception(e));
			map.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			map.put(ResultMsgConstants.ERR_MSG, "意向车型查询异常");
			map.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return map;
	}

	/*
	 * 保存客户信息
	 */
	@RequestMapping(value = "/saveTmKeep")
	public @ResponseBody Map<String, Object> saveTmKeep(TmKeep tmKeep, HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String infoMsg = null;
		try {
			String openId = request.getHeader(PointActivityConstant.HEADER_OPENID);
//			String openId = "oXrcfuC1R4wosEPeJOHR7BPqaAOo";

			// 查询客户表openId是否存在
			TmKeep tmKeeptmp = linkageService.getTmKeepByOpenId(openId);
			if (tmKeeptmp != null) {
				infoMsg = "请不要重复提交数据";
				resultMap.put("errorMs", infoMsg);
				return resultMap;
			} else {
				// 保存客户信息并返回主键
				tmKeep.setOpenId(openId);
				tmKeep.setCreateDate(new Date());
				linkageService.save(tmKeep);
				infoMsg = "恭喜您留资成功，请到选择的销售服务店领取精美小礼品一份";
				resultMap.put("infoMsg", infoMsg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("errorMs", "保存留资信息异常" + e.getMessage());
			logger.error("保存留资信息异常" + e.getMessage());
		}

		return resultMap;
	}

	/**
	 * 根据openid查询TmKeep是否有保存信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getTmKeep", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> findByTmKeep(HttpServletRequest req) {

		String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);
		// openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;

		Map<String, Object> map = new HashMap<>();
		TmKeep keep = linkageService.getTmKeepByOpenId(openId);
		map.put(keep.getDealerCode(), keep.getDealerName());
		return map;
	}

}
